import Popup from "@/components/Popup/Popup";
import { defineComponent, reactive, ref } from "vue";
import styles from "./Add.module.less";
import { PlusOutlined } from "@ant-design/icons-vue";
import _ from "lodash";
import { $upload } from "@/apis/common/upload/upload";
import to from "await-to-js";
import { message } from "ant-design-vue";


export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits:['change'],
  setup(props, { expose, emit }) {
    const addPopupRef = ref(null as any);
    const formRef = ref(null as any);
    const adding = ref(false);

    const state = reactive({
      type: 'add',
      form: {
        id: null,
        pid: null, //上级分类
        chineseName: null, //分类名称
        englishName: null, //分类英文名称
        image: null,//分类图标
        sort:null, //排序
        status:0, //状态
      },
      options:{
        pid:[
          {
            name:'顶级分类',
            id:0,
            children:[],
          },
        ]
      }
    } as any)

    const getDetail = async () => {
      const[err,res]:any = await to(props.service?.detail(state.form.id));
      if(!err){
        state.form.pid = res.data?.data?.pid;
        state.form.chineseName = res.data?.data?.chineseName;
        state.form.englishName = res.data?.data?.englishName;
        state.form.image = res.data?.data?.image;
        state.form.sort = res.data?.data?.sort;
        state.form.status = res.data?.data?.status;
      }
    }
    const getListTree = async () => {
      const [err,res]:any = await to(props.service?.listTree())
      if(!err){
        state.options.pid[0].children = res.data?.data.filter(x=>x.id !== state.form.id).map(x=>{
          delete x.children;
          return x;
        }) || [];
      }
    }
    //手动上传
    const imageUpload  = async (file) => {
      const formData = new FormData();
      formData.append("file", file);
      const [err,res]:any = await to($upload(formData));
      if (err) {
        message.error('上传失败，请重新上传')
        return;
      }
      state.form.image = res?.data?.url;
      message.success('上传成功')
      console.log(res);
      return false;
    }

    const submit = async () =>{
      adding.value = true;
      state.form.pid = ( state.form.pid  === null ? 0 : state.form.pid)
      const params = _.cloneDeep(state.form);
      if (!params.chineseName) {
        message.error('请输入分类名称');
        return;
      }
      if (!params.englishName) {
        message.error('请输入分类英文名称');
        return;
      }
      if (!params.image) {
        message.error('请上传分类图标');
        return;
      }
      if (!params.sort) {
        message.error('请上传分类图标');
        return;
      }
      const [err,res]:any = await to((state.type === 'add' ?props.service?.add : props.service?.edit)(params))
      if(!err){
        message.success('操作成功');
        emit('change');
        addPopupRef.value.close()
      }
      adding.value = false;
    }

    const open = async ({ type, id }) => {
      state.type = type;
      state.form.id = id || null;
      if (type === 'edit') {
        await getDetail()
      }
      await getListTree();
      addPopupRef.value.open();
    }

    expose({
      open,
    })
    return () => (
      <Popup
        ref={addPopupRef}
        title={state.type === 'add' ? '添加分类' : '编辑分类'}
        width="700px"
        oriState={state}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 18 }}>
              <a-form-item label="上级分类" name="pid">
                <a-tree-select
                  v-model:value={state.form.pid}
                  tree-data={state.options.pid}
                  placeholder="请选择上级分类"
                  fieldNames={{
                    label: 'name', value: 'id', children: 'children'
                  }}
                ></a-tree-select>
              </a-form-item>
              <a-form-item required label="分类名称" name="chineseName">
                <a-input v-model:value={state.form.chineseName} placeholder="请输入分类名称"/>
              </a-form-item>
              <a-form-item required label="分类英文名称" name="englishName">
                <a-input v-model:value={state.form.englishName} placeholder="请输入分类英文名称"/>
              </a-form-item>
              <a-form-item required label="分类图标" name="image">
                <div class={styles.imgBox}>
                  {
                    state.form.image && <img src={state.form.image}/>
                  }
                  <a-upload
                    before-upload={imageUpload}
                    showUploadList={false}
                    name="file"
                    >
                      <div class={styles.uploadBox}>
                        <PlusOutlined class={styles.icon}/>
                      </div>
                    </a-upload>
                </div>
              </a-form-item>
              <a-form-item required label="排序" name="sort">
                <a-input-number min={0} v-model:value={state.form.sort} placeholder="请输入排序" />
              </a-form-item>
              <a-form-item required label="状态" name="sort">
                <a-radio-group
                  v-model:value={state.form.status}
                  name="radioGroup"
                >
                  <a-radio value={0}>开启</a-radio>
                  <a-radio value={1}>关闭</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-form>
          </div>
          <div class={styles.footer}>
            <a-button type="primary" loading={adding.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }} style={{marginLeft:'20px'}}>取消</a-button>
          </div>
        </div>
      </Popup>
    )
  }
})